package com.ruoyi.web.controller.system;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.SmsLoginBody;
import com.ruoyi.common.core.domain.model.WeChatLoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.law.utils.SmsUtil;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(tags = "登录验证")
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 微信注册、登录
     *
     * @param weChatLoginBody 登录信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("微信注册、登录")
    @PostMapping("/weChatLogin")
    public R<String> weChatLogin(@Validated @RequestBody WeChatLoginBody weChatLoginBody) {
        String openid = sysUserService.getOpenid(weChatLoginBody.getCode());
        // 检查用户是否存在，不存在则注册
        checkUser(weChatLoginBody, openid);

        LoginBody loginBody = new LoginBody();
        loginBody.setUsername(openid);
        loginBody.setPassword("noPassWord");

        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        return R.ok(token);
    }

    @RepeatSubmit
    @Anonymous
    @ApiOperation("发送验证码")
    @ApiImplicitParam(name = "phone", value = "手机号", required = true)
    @PostMapping("/sendCode")
    public R<String> sendCode(@RequestBody String phone) throws ClientException {
        // 校验手机号
        Assert.isTrue(PhoneUtil.isMobile(phone), "手机号格式不正确");
        String code = RandomUtil.randomNumbers(6);
        // TODO 上线前解开限制
        SmsUtil.send(phone, code);
        // 缓存验证码和手机号(5分钟有效)
        redisCache.setCacheObject(phone, code, 5, TimeUnit.MINUTES);

        return R.ok(code);
    }

    /**
     * 手机号码登录
     *
     * @param smsLoginBody 登录信息
     * @return 结果
     */
    @Anonymous
    @ApiOperation("手机号码登录")
    @PostMapping("/smsLogin")
    public R<String> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
        // 检查手机号和验证码是否匹配
        String phone = smsLoginBody.getPhone();
        String code = redisCache.getCacheObject(phone);
        Assert.isTrue(smsLoginBody.getCode().equals(code), "验证码错误");

        SysUser user = sysUserService.selectUserByPhone(phone);
        if (user == null) {
            // 注册用户
            user = new SysUser();
            //不需要部门
            user.setDeptId(100L);
            user.setUserName(IdUtil.fastSimpleUUID());
            user.setNickName(phone);
            user.setPhonenumber(phone);
            user.setAvatar("/profile/upload/2023/01/04/user_20230104151157A001.jpg");
            user.setAmount(BigDecimal.ZERO);
            user.setAmountFrozen(BigDecimal.ZERO);
            // 0普通用户 1vip 2svip
            user.setVipId(0L);
            user.setUserType("-1");
            user.setPassword(SecurityUtils.encryptPassword("noPassWord"));
            sysUserService.insertUser(user);
        }
        LoginBody loginBody = new LoginBody();
        loginBody.setUsername(user.getUserName());
        loginBody.setPassword("noPassWord");

        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        return R.ok(token);
    }


    /**
     * 检查用户是否存在，不存在则注册
     *
     * @param weChatLoginBody 登录信息
     * @param openid          openid
     */
    private void checkUser(WeChatLoginBody weChatLoginBody, String openid) {
        SysUser user = sysUserService.selectUserByOpenid(openid);
        // 没有就新增用户
        if (user == null) {
            user = new SysUser();
            //不需要部门
            user.setDeptId(100L);
            user.setOpenid(openid);
            user.setUserName(openid);
            user.setNickName(weChatLoginBody.getName());
            user.setPhonenumber(weChatLoginBody.getPhone());
            user.setAvatar(weChatLoginBody.getHeadPortrait());
            user.setInvitationId(weChatLoginBody.getInvitationId());
            user.setAmount(BigDecimal.ZERO);
            user.setAmountFrozen(BigDecimal.ZERO);
            // 0普通用户 1vip 2svip
            user.setVipId(0L);
            user.setUserType("-1");
            user.setPassword(SecurityUtils.encryptPassword("noPassWord"));
            sysUserService.insertUser(user);
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
